﻿package com.thorqq.magictimer;

import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baidu.mobstat.StatService;
import com.thorqq.magictimer.action.ActionKlaxon;
import com.thorqq.magictimer.misc.FileOperator;
import com.thorqq.magictimer.timeLoop.TimerMgr;
import com.thorqq.magictimer.util.Util;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MusicBrowserActivity extends FragmentActivityBase
{

    public static final String SYSTEM_AUDIO_PATH = "/system/media/audio/";
    public static final String SYSTEM_AUDIO_ALARMS_PATH = "/system/media/audio/alarms";
    public static final String SYSTEM_AUDIO_RINGTONES_PATH = "/system/media/audio/ringtones";
    public static final String SYSTEM_AUDIO_NOTIFICATIONS_PATH = "/system/media/audio/notifications";

    private List<Fragment> mFragmentList = new ArrayList<Fragment>();
    private List<String>   mTitleList    = new ArrayList<String>();
    
    private String mMusicPath;
    private ActionKlaxon mAction;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        mAction = (ActionKlaxon)getIntent().getExtras().getSerializable(TimerMgr.ALARM_INTENT_ACTION);
        mMusicPath = mAction.getParam();
        
        Util.log("Old music: " + mMusicPath);

        initLayout();
        updateLayout();
        regListener();
    }
    
    private void regListener()
    {

    }

    private void initLayout()
    {        
        super.setBottonLayoutVisibility(View.VISIBLE);
                
        mFragmentList.add(new FragmentAudio(this, SYSTEM_AUDIO_ALARMS_PATH, false));
        mTitleList.add("闹铃");
    
        mFragmentList.add(new FragmentAudio(this, SYSTEM_AUDIO_RINGTONES_PATH, false));
        mTitleList.add("铃声");
        
        mFragmentList.add(new FragmentAudio(this, SYSTEM_AUDIO_NOTIFICATIONS_PATH, false));
        mTitleList.add("通知音");
       
        mFragmentList.add(new FragmentAudio(this, Util.getSDCardRootDir().getAbsolutePath(), true));
        mTitleList.add("存储卡");

        super.setFragmentList(mFragmentList, mTitleList);
    }

    private void updateLayout()
    {
        for(Fragment f : mFragmentList)
        {
            FragmentAudio ff = (FragmentAudio)f;
            ff.notifyMusicPathChanged();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        stopService(new Intent(TimerMgr.MEDIA_PLAY));
        
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void doOnClickSave()
    {
        mAction.setMusicPath(mMusicPath);
        Util.log("New music: " + mMusicPath);
        
        Intent i = new Intent();
        i.putExtra(TimerMgr.ALARM_INTENT_ACTION, mAction);
        setResult(RESULT_OK, i);
        finish();
    }

    @Override
    protected void doOnClickCancel()
    {
        finish();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        StatService.onPause(this);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        StatService.onResume(this);
    }

    public class FragmentAudio extends Fragment 
    {

        private Context mContext;
//        private String mAudioPath;
        private List<File> mFileList = new ArrayList<File>();
        private ArrayList<Map<String, Object>> mFileItemList = new ArrayList<Map<String, Object>>();
        private AdapterFileBrowser mFileBrowserAdapter;
        private boolean mHasReturnDir = false;
        
        private File mFileParent;
//        private File mFileCurrent;
        
        private View mView;
        private ViewGroup mViewGroup;
        private ListView mListView;
        private RelativeLayout mLayout;
        private ProgressBar mProgress;
        
        public FragmentAudio(Context context, String path, boolean hasReturnDir)
        {
            super();
            
            mContext = context;
            mFileParent = new File(path);
            mHasReturnDir = hasReturnDir;            
        }

        
        @Override
        public void onDestroyView()
        {
            if(mViewGroup != null)
            {
                mViewGroup.removeAllViews();
            }
            super.onDestroyView();
        }

        @Override
        public void onPause()
        {
            mContext.stopService(new Intent(TimerMgr.MEDIA_PLAY));
            super.onPause();
        }
        
        public void notifyMusicPathChanged()
        {
            if(mFileBrowserAdapter != null)
            {
                mFileBrowserAdapter.setFilePath(mMusicPath);
                mFileBrowserAdapter.notifyDataSetChanged();
            }
        }
        
        public View makeView()
        {
            Util.log("FragmentAudio.makeView: " + mFileParent.getAbsolutePath());
            
            //载入动画
            mProgress = new ProgressBar(mContext);
            mProgress.setVisibility(View.GONE);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.CENTER_IN_PARENT);
            mProgress.setLayoutParams(params);
            
            //文件列表
            mListView = new ListView(mContext);
            mListView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            mListView.setCacheColorHint(0x00000000);
            mListView.setFastScrollEnabled(true);

            mFileBrowserAdapter = new AdapterFileBrowser(mContext, mFileItemList);
            mFileBrowserAdapter.setFilePath(mMusicPath);
            mListView.setAdapter(mFileBrowserAdapter);
            mListView.setDivider(mContext.getResources().getDrawable(R.drawable.gradient_shape_hor));
            mListView.setDividerHeight(1);
            
            //
            mLayout = new RelativeLayout(mContext);
            mLayout.addView(mProgress);
            mLayout.addView(mListView);

            this.listFiles();

            mListView.setOnItemClickListener(new OnItemClickListener(){

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
                {
                    mContext.stopService(new Intent(TimerMgr.MEDIA_PLAY));
                    
                    File file = mFileList.get(position);
                    //点击的是目录，且有权限
                    if (file.isDirectory() && file.canRead())
                    {

                        File[] f = file.listFiles();
                        if (f.length > 0)
                        {
                            //返回上一级目录
                            if(mFileParent.getAbsolutePath().equals(file.getAbsolutePath()))
                            {
                                if(mFileParent.getParentFile() == null)
                                {
                                    Toast.makeText(mContext, "已经是根目录", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                else
                                {
                                    mFileParent = mFileParent.getParentFile();
                                }
                            }
                            else
                            {
                                mFileParent = file;
                            }
                            listFiles();
                        } 
                        else
                        {
                            Toast.makeText(mContext, file.getName()+"文件夹为空", Toast.LENGTH_SHORT).show();
                        }

                    } 
                    //点击的是目录，但没有权限
                    else if(file.isDirectory() && !file.canRead())
                    {
                        Toast.makeText(mContext, file.getName()+"没有访问权限", Toast.LENGTH_SHORT).show();
                    }
                    //点击的是文件
                    else
                    {
                        mMusicPath = file.getAbsolutePath();
                        mFileBrowserAdapter.setFilePath(mMusicPath);
//                        mFileBrowserAdapter.notifyDataSetChanged();
                        MusicBrowserActivity.this.updateLayout();
                        
                        Intent playAlarm = new Intent(TimerMgr.MEDIA_PLAY);
                        playAlarm.putExtra(TimerMgr.ALARM_INTENT_MUSIC_PATH, file.getAbsolutePath());
                        playAlarm.putExtra(TimerMgr.ALARM_INTENT_MUSIC_LOOP, false);
                        mContext.startService(playAlarm);
                    }
                }
            });
            
            return mLayout;
        }
        
        // 读取文件列表,并设置listView
        public void listFiles()
        {
            mProgress.setVisibility(View.VISIBLE);
            
            new AsyncTask<File, String, String>()
            {
                protected String doInBackground(File... params)
                {
                    FileOperator.listMusicFiles(MusicBrowserActivity.this, mFileParent, mFileList);
                    return null;
                }

                protected void onPostExecute(String result)
                {               
                    mFileItemList.clear();
                    
                    for (int i = 0; i < mFileList.size(); i++)
                    {
                        File file = mFileList.get(i);
                        String end = file.getName().substring(file.getName().lastIndexOf(".") + 1)
                                .toLowerCase();
                        boolean isFile = file.isFile();

                        HashMap<String, Object> hashMap = new HashMap<String, Object>();

                        hashMap.put("filePath", file.getAbsolutePath());
                        hashMap.put("fileIcon", getFileIcon(MusicBrowserActivity.this, file, end));
                        hashMap.put("fileName", file.getName());

                        if (isFile)
                        {
                            hashMap.put("fileInfo",
                                    new Date(file.lastModified()).toString() + "  " + Util.sizeFormat(file.length()));
                        } 
                        else
                        {
                            hashMap.put("fileInfo", new Date(file.lastModified()).toString());
                        }
                        
                        mFileItemList.add(hashMap);
                    }

                    //返回上一级目录
                    if(mHasReturnDir && mFileParent.getParentFile() != null)
                    {
                        HashMap<String, Object> hashMapPre = new HashMap<String, Object>();
                        hashMapPre.put("filePath", mFileParent.getAbsolutePath());
                        hashMapPre.put("fileIcon", R.drawable.directory);
                        hashMapPre.put("fileName", "..");
                        hashMapPre.put("fileInfo", "上一级文件夹");
                        mFileItemList.add(0, hashMapPre);
                        mFileList.add(0, mFileParent);
                    }
                    
                    mProgress.setVisibility(View.GONE);
                    mFileBrowserAdapter.notifyDataSetChanged();
                   
                    super.onPostExecute(result);
                }
            }.execute();
        }
        
        private Object getFileIcon(Context context, File file, String end)
        {
            if (file.isDirectory())
            {
                return R.drawable.directory;
            } 
            
            for(int i = 0; i < FileOperator.musicEnd.length; i++)
            {
                if(end != null && end.equalsIgnoreCase(FileOperator.musicEnd[i]))
                {
                    return R.drawable.music_note;
                }
            }
            
            return R.drawable.others;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        {                                                
            mViewGroup = new LinearLayout(mContext);
            
            if(mView == null)
            {
                mView = this.makeView();
            }
            
            mViewGroup.addView(mView);
            
            return mViewGroup;
        }
    }

}
